<template>
  <el-dialog :visible="isShowDialog" :title="formData.id ? '编辑分类' : '添加分类'" @close="close">
    <el-form ref="formData" :model="formData" :rules="rules" label-width="50px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="封面" prop="image">
        <ImageUpload ref="Upload" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="btnOk">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { editCategory, addCategory } from '@/api/category'
export default {
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        desc: '',
        image: ''
      },
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    close() {
      this.$emit('update:isShowDialog', false)
      // 页面关闭后对表单进行初始化
      this.formData = {
        title: '',
        desc: '',
        image: ''
      }
      this.$refs.Upload.fileList = []
    },
    async btnOk() {
      // 校验表单
      await this.$refs.formData.validate()
      const fileList = this.$refs.Upload.fileList
      // 如果有图片, 但是图片没有上传完毕, 应该警告并阻挡请求发送
      if (fileList[0] && fileList[0].status !== 'success') {
        this.$message.warning('请耐心等待图片上传完毕')
        return
      }
      const data = {
        ...this.formData,
        image: fileList[0] ? fileList[0].url : null
      }
      if (this.formData.id) {
        await editCategory(data)
      } else {
        await addCategory(data)
      }
      this.$message.success('操作成功')
      this.close()
      this.$emit('reload')
    }
  }
}
</script>

<style scoped>
.pic {
    height: 145px;
    object-fit: contain;
}
</style>
